<!-- 添加任务页面 -->
<template>
  <view class="add-task-page">
    <!-- 导航栏 -->
    <NavBar title="添加任务" showBack="true"></NavBar>
    
    <!-- 主内容区域 -->
    <view class="main-content">
      <!-- 任务表单 -->
      <view class="task-form">
        <!-- 任务标题 -->
        <view class="input-group">
          <label>任务标题 *</label>
          <input type="text" v-model="task.title" placeholder="例如：英语单词学习" @input="onInputChange('title')" class="custom-input"/>
        </view>
        
        <!-- 任务描述 -->
        <view class="input-group">
          <label>任务描述</label>
          <textarea v-model="task.description" placeholder="添加任务的详细说明" @input="onInputChange('description')" class="custom-textarea"></textarea>
        </view>
        
        <!-- 周期性任务设置 -->
        <view class="input-group">
          <div class="flex-between items-center">
            <label>周期性任务</label>
            <!-- 自定义开关按钮 -->
            <view 
              class="custom-toggle" 
              :class="{ active: task.isRecurring }"
              @click="toggleRecurring"
            >
              <view class="toggle-slider"></view>
            </view>
          </div>
        </view>
        
        <!-- 跳过节假日设置 - 仅在周期性任务开启时显示 -->
        <template v-if="task.isRecurring">
          <view class="input-group">
            <div class="flex-between items-center">
              <label>跳过节假日</label>
              <!-- 自定义开关按钮 -->
              <view 
                class="custom-toggle" 
                :class="{ active: task.skipHolidays }"
                @click="toggleSkipHolidays"
              >
                <view class="toggle-slider"></view>
              </view>
            </div>
          </view>
        </template>
        
        <!-- 周期性任务：选择星期 -->
        <template v-if="task.isRecurring">
          <view class="input-group">
            <label>选择重复的星期 *</label>
            <view class="weekday-selection">
              <!-- 全选按钮 -->
              <view 
                class="weekday-item" 
                :class="{ 'selected': selectedWeekdays.length === weekdays.length && weekdays.length > 0 }"
                @click="toggleSelectAllWeekdays"
              >
                全选
              </view>
              <!-- 星期选项 -->
              <view 
                v-for="day in weekdays" 
                :key="day.value"
                :class="['weekday-item', { 'selected': selectedWeekdays.includes(day.value) }]"
                @click="toggleWeekday(day.value)"
              >
                {{ day.label }}
              </view>
            </view>
          </view>
        </template>
        
        <!-- 共用的开始时间和持续时间 -->
        <view class="input-group">
          <label>开始时间 *</label>
          <!-- 用户手动输入时间 -->
          <input 
            type="text" 
            v-model="task.startTime" 
            @input="onInputChange('startTime')"
            class="custom-input" 
            placeholder="请输入时间，格式：HH:MM（例如：14:30）"
          />
        </view>
        
        <!-- 持续时间 -->
        <view class="input-group">
          <label>持续时间（分钟）*</label>
          <input type="number" v-model.number="task.duration" placeholder="输入任务持续时间" @input="onInputChange('duration')" class="custom-input"/>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <uni-button type="default" @click="saveDraft">保存草稿</uni-button>
        <uni-button type="primary" class="btn-primary" @click="addTask">添加任务</uni-button>
      </view>
    </view>
  </view>
</template>

<script>
// 导入组件
import NavBar from '../../components/NavBar.vue'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      // 任务数据
      task: {
        title: '',
        description: '',
        startTime: '',
        duration: '',
        isRecurring: false,
        skipHolidays: false,
        isCompleted: false
      },
      // 星期选项
      weekdays: [
        { value: 'monday', label: '周一' },
        { value: 'tuesday', label: '周二' },
        { value: 'wednesday', label: '周三' },
        { value: 'thursday', label: '周四' },
        { value: 'friday', label: '周五' },
        { value: 'saturday', label: '周六' },
        { value: 'sunday', label: '周日' }
      ],
      // 选中的星期
      selectedWeekdays: []
    }
  },
  onLoad() {
    // 页面加载时，如果有草稿，可以从本地存储加载
    const draftTask = uni.getStorageSync('draftTask')
    if (draftTask) {
      this.task = { ...draftTask }
    }
  },
  methods: {
    // 自定义切换周期性任务状态
    toggleRecurring() {
      // 切换任务的周期性状态
      this.task.isRecurring = !this.task.isRecurring
      console.log('周期性任务状态变化为:', this.task.isRecurring)
      // 如果关闭周期性任务，清空选中的星期
      if (!this.task.isRecurring) {
        this.selectedWeekdays = []
      }
    },
    
    // 切换跳过节假日状态
    toggleSkipHolidays() {
      // 切换是否跳过节假日的状态
      this.task.skipHolidays = !this.task.skipHolidays
      console.log('跳过节假日状态变化为:', this.task.skipHolidays)
    },
    
    // 全选/取消全选星期
    toggleSelectAllWeekdays() {
      if (this.selectedWeekdays.length === this.weekdays.length) {
        // 如果已全选，则取消全选
        this.selectedWeekdays = []
      } else {
        // 如果未全选，则全选
        this.selectedWeekdays = this.weekdays.map(day => day.value)
      }
      console.log('全选后的星期:', this.selectedWeekdays)
    },
    
    // 切换星期选择
    toggleWeekday(dayValue) {
      const index = this.selectedWeekdays.indexOf(dayValue)
      if (index > -1) {
        // 如果已选中，则取消选择
        this.selectedWeekdays.splice(index, 1)
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedWeekdays.push(dayValue)
      }
      console.log('选中的星期:', this.selectedWeekdays)
    },
    

    
    // 输入框变化
    onInputChange(field) {
      console.log(`${field} 输入内容:`, this.task[field])
    },
    
    // 日期时间选择变化
    onDateTimeChange(e) {
      console.log('选择的开始时间:', this.task.startTime)
    },
    
    // 保存草稿
    saveDraft() {
      // 保存到本地存储
      uni.setStorageSync('draftTask', this.task)
      // 显示保存成功提示
      uni.showToast({
        title: '草稿已保存',
        icon: 'success'
      })
    },
    
    // 添加任务
    addTask() {
      // 表单验证
      if (!this.task.title.trim()) {
        uni.showToast({
          title: '请输入任务标题',
          icon: 'none'
        })
        return
      }
      
      if (!this.task.startTime) {
        uni.showToast({
          title: '请输入开始时间',
          icon: 'none'
        })
        return
      }
      
      // 验证时间格式是否为HH:MM
      const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
      if (!timeRegex.test(this.task.startTime)) {
        uni.showToast({
          title: '时间格式不正确，请使用HH:MM格式',
          icon: 'none'
        })
        return
      }
      
      if (!this.task.duration || this.task.duration <= 0) {
        uni.showToast({
          title: '请输入有效的持续时间',
          icon: 'none'
        })
        return
      }
      
      if (this.task.isRecurring && this.selectedWeekdays.length === 0) {
        uni.showToast({
          title: '请至少选择一个重复的星期',
          icon: 'none'
        })
        return
      }
      
      // 为周期性任务添加必要的字段
      const taskToAdd = {
        ...this.task,
        // 确保所有必要字段都有默认值
        recurrencePattern: this.task.isRecurring ? 'weekly' : '', // 默认设为weekly
        skipHolidays: this.task.skipHolidays || false
      }
      
      if (this.task.isRecurring) {
        taskToAdd.selectedWeekdays = this.selectedWeekdays
        // 根据选中的星期数量确定重复模式
        if (this.selectedWeekdays.length === 7) {
          taskToAdd.recurrencePattern = 'daily'
        } else if (this.selectedWeekdays.length >= 5 && 
                  this.selectedWeekdays.includes('monday') && 
                  this.selectedWeekdays.includes('tuesday') && 
                  this.selectedWeekdays.includes('wednesday') && 
                  this.selectedWeekdays.includes('thursday') && 
                  this.selectedWeekdays.includes('friday')) {
          taskToAdd.recurrencePattern = 'workdays'
        } else {
          taskToAdd.recurrencePattern = 'weekly'
        }
      }
      
      // 添加任务到Vuex - 传递包含所有必要属性的任务对象
      this.$store.commit('addTask', taskToAdd)
      
      // 清除草稿
      uni.removeStorageSync('draftTask')
      
      // 显示添加成功提示
      uni.showToast({
        title: '任务添加成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      })
    }
  },
  // 页面卸载时，如果有未保存的任务，自动保存为草稿
  onUnload() {
    if (this.task.title || this.task.description || this.task.duration) {
      this.saveDraft()
    }
  }
}
</script>

<style scoped>
.add-task-page {
  padding-top: 88rpx; /* 导航栏高度 */
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  padding: 20rpx;
}

.task-form {
  background-color: white;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.input-group {
  margin-bottom: 30rpx;
}

.input-group label {
  display: block;
  margin-bottom: 10rpx;
  color: #666;
  font-size: 28rpx;
}

/* 自定义输入框样式 */
      .custom-input {
        width: 100%;
        height: 80rpx;
        border: 2rpx solid #ddd;
        border-radius: 8rpx;
        padding: 0 20rpx;
        background-color: white;
        font-size: 28rpx;
        box-sizing: border-box;
      }
      

      
      /* 自定义文本域样式 */
      .custom-textarea {
        width: 100%;
        height: 160rpx;
        border: 2rpx solid #ddd;
        border-radius: 8rpx;
        padding: 20rpx;
        background-color: white;
        font-size: 28rpx;
        resize: none;
        box-sizing: border-box;
      }

      /* flex布局 - 两端对齐 */
      .flex-between {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      

      
      /* 自定义开关按钮样式 */
      .custom-toggle {
        width: 100rpx;
        height: 56rpx;
        background-color: #ccc;
        border-radius: 56rpx;
        position: relative;
        transition: background-color 0.3s;
        display: flex;
        align-items: center;
        padding: 4rpx;
      }
      
      .custom-toggle.active {
        background-color: #4CAF50;
      }
      
      .toggle-slider {
        width: 48rpx;
        height: 48rpx;
        background-color: white;
        border-radius: 50%;
        position: absolute;
        left: 4rpx;
        transition: transform 0.3s;
      }
      
      .custom-toggle.active .toggle-slider {
        transform: translateX(44rpx);
      }
      
      /* 星期选择样式 */
      .weekday-selection {
        display: flex;
        flex-wrap: wrap;
        gap: 15rpx;
        padding: 10rpx 0;
      }
      
      .weekday-item {
        padding: 15rpx 25rpx;
        border: 2rpx solid #ddd;
        border-radius: 30rpx;
        font-size: 26rpx;
        color: #666;
        background-color: white;
        text-align: center;
        transition: all 0.3s;
      }
      
      .weekday-item.selected {
        background-color: #4CAF50;
        color: white;
        border-color: #4CAF50;
      }

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 0 20rpx;
  justify-content: center;
}

.action-buttons uni-button {
  flex: 1;
  font-size: 28rpx;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  text-align: center;
}

.action-buttons uni-button[type="default"] {
  background-color: #d0d0d0 !important;
  color: #333 !important;
}

.btn-primary {
  background-color: #4CAF50 !important;
  color: white !important;
}
</style>